/*
 * @(#)SmsModemAdapter.java
 * 2014-09-20 上午10:42:34
 * 
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.inf.sms;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.smslib.AGateway;
import org.smslib.GatewayException;
import org.smslib.IOutboundMessageNotification;
import org.smslib.Library;
import org.smslib.OutboundMessage;
import org.smslib.SMSLibException;
import org.smslib.Service;
import org.smslib.TimeoutException;
import org.smslib.Message.MessageEncodings;
import org.smslib.modem.SerialModemGateway;

import com.qyxx.platform.common.utils.httpclient.HttpClientUtils;
import com.qyxx.platform.inf.adapter.AdapterException;
import com.qyxx.platform.inf.adapter.AdapterProperties;
import com.qyxx.platform.inf.adapter.INeiAdapter;
import com.qyxx.platform.inf.adapter.NeiTask;


/**
 *  通用短信猫接口
 *  @author gxj
 *  @version 1.0 2014-09-20 上午10:42:34
 *  @since jdk1.6 
 */

public class SmsModemAdapter implements INeiAdapter {

	private AdapterProperties ap;
	
	private Map<String, String> paramMap = new HashMap<String,String>();
	
	/**
	 * 初始化接口适配器
	 * @see com.qyxx.platform.inf.adapter.INeiAdapter#init(com.qyxx.platform.inf.adapter.AdapterProperties)
	 */
	@Override
	public void init(AdapterProperties adapterProperties)
															throws AdapterException {
		this.ap = adapterProperties;
		
		String id = ap.getAdapterCode();
		String port = ap.getUserName();
		String rate = ap.getPassword();
		String manuf = ap.getParamValue("productid");
		
		OutboundNotification outboundNotification = new OutboundNotification();
		//System.out.println("Example: Send message from a serial gsm modem.");
		//System.out.println(Library.getLibraryDescription());
		//System.out.println("Version: " + Library.getLibraryVersion());
		
		SerialModemGateway gateway = new SerialModemGateway(id, port, NumberUtils.toInt(rate, 115200), 
				StringUtils.defaultIfEmpty(manuf, "HuaWei"), "");
		gateway.setInbound(true);
		gateway.setOutbound(true);
		gateway.setSimPin("0000");
		// Explicit SMSC address set is required for some modems.
		// Below is for VODAFONE GREECE - be sure to set your own!
		//gateway.setSmscNumber("+306942190000");
		Service.getInstance().setOutboundMessageNotification(outboundNotification);
		try {
			Service.getInstance().addGateway(gateway);
			Service.getInstance().startService();
		} catch (Exception e) {
			throw new AdapterException("启动短信猫服务出现异常", e);
		}
		
	}
	
	public class OutboundNotification implements IOutboundMessageNotification
	{
		public void process(AGateway gateway, OutboundMessage msg)
		{
			//System.out.println("Outbound handler called from Gateway: " + gateway.getGatewayId());
			//System.out.println(msg);
		}
	}

	/**
	 * 处理指令
	 * @see com.qyxx.platform.inf.adapter.INeiAdapter#handle(com.qyxx.platform.inf.adapter.NeiTask)
	 */
	@Override
	public NeiTask handle(NeiTask task) throws AdapterException {
		String mobile = StringUtils.replace(task.getTargetCode(), ";", ",");//替换分号为逗号
		String content= task.getCmd();
		OutboundMessage msg = new OutboundMessage(mobile, content);
		msg.setEncoding(MessageEncodings.ENCUCS2);
		boolean result;
		try {
			result = Service.getInstance().sendMessage(msg);
			task.setIsReturnSuccess(result);
			if(!result) {
				task.setReport(msg.getErrorMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
			task.setIsReturnSuccess(false);
			task.setReport(e.getMessage());
		}
		return task;
	}

	@Override
	public String handle(String... task) throws AdapterException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isHaveIdleInteractant() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void destroy() throws AdapterException {
		// TODO Auto-generated method stub
		try {
			Service.getInstance().stopService();
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.ap = null;
		this.paramMap.clear();
		this.paramMap = null;
	}

	@Override
	public AdapterProperties getAdapterProperties() {
		// TODO Auto-generated method stub
		return ap;
	}

	@Override
	public void setAdapterProperties(
			AdapterProperties adapterProperties) {
		this.ap = adapterProperties;
	}
	
	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		INeiAdapter nei = new SmsModemAdapter();
		AdapterProperties testAp = new AdapterProperties();
		testAp.setAdapterCode("sms001");
		testAp.setUserName("COM12");
		testAp.setPassword("115200");
		testAp.setParamValue("productid", "Huawei");
		try {
			nei.init(testAp);
			NeiTask task = new NeiTask();
			task.setTargetCode("15305812560");
			task.setCmd("测试短信，仅供测试使用，谢谢");
			NeiTask result = nei.handle(task);
			System.out.println(result.getReport() + result.getIsReturnSuccess());
		} catch (AdapterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
